package xuhaijia.lanou3g.autohome.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

import xuhaijia.lanou3g.autohome.R;
import xuhaijia.lanou3g.autohome.base.BaseActivity;
import xuhaijia.lanou3g.autohome.base.NetTool;
import xuhaijia.lanou3g.autohome.base.StringValues;
import xuhaijia.lanou3g.autohome.base.URLValues;
import xuhaijia.lanou3g.autohome.custom.PinnedHeaderListView;
import xuhaijia.lanou3g.autohome.custom.ToastCustom;
import xuhaijia.lanou3g.autohome.find.FindFragment;
import xuhaijia.lanou3g.autohome.findcar.FindCarFragment;
import xuhaijia.lanou3g.autohome.forum.ForumFragment;
import xuhaijia.lanou3g.autohome.forum.normalforum.CarTypeAdapter;
import xuhaijia.lanou3g.autohome.forum.normalforum.CarTypeBean;
import xuhaijia.lanou3g.autohome.forum.normalforum.LocationForumAdapter;
import xuhaijia.lanou3g.autohome.forum.normalforum.LocationForumBean;
import xuhaijia.lanou3g.autohome.forum.normalforum.OrderAdapter;
import xuhaijia.lanou3g.autohome.forum.normalforum.ThemeAdapter;
import xuhaijia.lanou3g.autohome.forum.normalforum.ThemeBean;
import xuhaijia.lanou3g.autohome.myself.MyselfFragment;
import xuhaijia.lanou3g.autohome.recommend.RecommendFragment;
import xuhaijia.lanou3g.autohome.recommend.video.VideoTypeAdapter;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private ImageView searchIv;
    private RecommendFragment recommendFragment;
    private ImageView modeIv;
    private DrawerLayout drawerLayout;
    private RelativeLayout layoutForDrawer;
    private MenuReceiver receiver;
    private View carTypeView;
    private ListView rightLv;
    private CarTypeAdapter carTypeAdapter;
    private PinnedHeaderListView leftLv;
    private String[] letter = StringValues.order;
    private String[] locationOrder = StringValues.loacationOrder;
    private ArrayList<ArrayList<String>> name;
    private ArrayList<HashMap<String, String>> type;
    private OrderAdapter orderAdapter;
    private TextView closeTv;
    private View locationView;
    private TextView locationCloseTv;
    private ListView locationRightLv;
    private PinnedHeaderListView locationLeftLv;
    private LocationForumAdapter locationForumAdapter;
    private View themeView;
    private TextView themeClose;
    private ThemeAdapter themeAdapter;
    private ListView themeLv;
    private View videoView;
    private TextView videoClose;
    private ListView videoLv;
    private VideoTypeAdapter videoTypeAdapter;
    private ImageView changModeIv;
    private boolean isNightMode;
    private SharedPreferences shared;


    @Override
    protected int setLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        searchIv = bindView(R.id.iv_search);
        searchIv.bringToFront();
        searchIv.setOnClickListener(this);
        modeIv = bindView(R.id.iv_mode);
        modeIv.bringToFront();
        modeIv.setOnClickListener(this);
        RadioGroup radioGroup = bindView(R.id.radio_group_main);
        radioGroup.setOnCheckedChangeListener(this);
        radioGroup.check(R.id.recommend_btn);
        layoutForDrawer = bindView(R.id.relative_layout_fordrawer);
        drawerLayout = bindView(R.id.main_drawer_layout_all);
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        changModeIv = bindView(R.id.change_mode_iv);
        changModeIv.bringToFront();
        shared = getPreferences(MODE_PRIVATE);
        if (shared.getBoolean("night" ,false)) {
            changModeIv.setVisibility(View.VISIBLE);
            modeIv.setImageResource(R.mipmap.sunshine);
        } else {
            changModeIv.setVisibility(View.GONE);
            modeIv.setImageResource(R.mipmap.moon);
        }

    }




    @Override
    protected void initData() {
//        toastCustom = new ToastCustom();
        receiver = new MenuReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(StringValues.CARTYPE);
        filter.addAction(StringValues.LOCATION);
        filter.addAction(StringValues.THEME);
        filter.addAction(StringValues.VIDEO);
        registerReceiver(receiver, filter);

    }

    public void drawDrawer() {
        carTypeDrawable();
        locationDrawable();
        themeDrawable();

    }
    public void videoDrawer(){
        videoTypeDrawable();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search:
                Intent intent = new Intent(MainActivity.this , SeachActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_mode:
                SharedPreferences.Editor editor = shared.edit();
                if (shared.getBoolean("night" ,false)) {
                    changModeIv.setVisibility(View.GONE);
                    editor.putBoolean("night" , false);
                    modeIv.setImageResource(R.mipmap.moon);
                } else {
                    changModeIv.setVisibility(View.VISIBLE);
                    editor.putBoolean("night" , true);
                }
                editor.apply();
                break;
        }
    }

    public class MenuReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            layoutForDrawer.bringToFront();
            if (action.equals(StringValues.CARTYPE)) {
                if (carTypeView == null) {
                    carTypeDrawable();
                }
                layoutForDrawer.addView(carTypeView);
            }
            if (action.equals(StringValues.LOCATION)) {
                if (locationView == null) {
                    locationDrawable();
                }
                layoutForDrawer.addView(locationView);

            }
            if (action.equals(StringValues.THEME)) {
                if (themeView == null) {
                    themeDrawable();
                }
                layoutForDrawer.addView(themeView);
            }
            if (action.equals(StringValues.VIDEO)) {
                if (videoView == null) {
                    videoTypeDrawable();
                }
                layoutForDrawer.addView(videoView);
            }

            openRightLayout();
            initEvent();

        }
    }


    private void carTypeDrawable() {
        carTypeView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.right_drawer_car_type, null);
        closeTv = (TextView) carTypeView.findViewById(R.id.drawer_cartypeforum_close);
        closeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openRightLayout();
                layoutForDrawer.removeView(carTypeView);
            }
        });
        rightLv = (ListView) carTypeView.findViewById(R.id.drawe_cartype_right_lv);
        leftLv = (PinnedHeaderListView) carTypeView.findViewById(R.id.drawer_cartype_left_lv);

        orderAdapter = new OrderAdapter(this);
        orderAdapter.setOrder(letter);
        rightLv.setAdapter(orderAdapter);
        rightLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int rightSection = 0;
                for (int i = 0; i < position; i++) {
                    rightSection += carTypeAdapter.getCountForSection(i) + 1;
                }
                leftLv.setSelection(rightSection);
//                toastCustom.getToast(getApplicationContext(), letter[position]);
                ToastCustom.showText(getApplicationContext(),letter[position]);

            }
        });
        mNetTool.getNetData(URLValues.CAR_TYPE_URL, CarTypeBean.class, new NetTool.NetListener<CarTypeBean>() {
            @Override
            public void onSuccess(CarTypeBean carTypeBean) {
                name = new ArrayList<>();
                ArrayList<String> a = new ArrayList<>();
                type = new ArrayList<>();
                HashMap<String, String> b = new HashMap<>();
                for (int num = 0; num < letter.length; num++) {
                    for (int i = 0; i < carTypeBean.getResult().getList().size(); i++) {
                        if (carTypeBean.getResult().getList().get(i).getLetter().equals(letter[num])) {
                            a.add(carTypeBean.getResult().getList().get(i).getBrandname());
                            b.put(carTypeBean.getResult().getList().get(i).getBrandname()
                                    , carTypeBean.getResult().getList().get(i).getBrandimg());
                        }
                    }
                    name.add(a);
                    type.add(b);
                    a = new ArrayList<>();
                    b = new HashMap<>();
                }
                carTypeAdapter = new CarTypeAdapter(getApplicationContext());
                carTypeAdapter.setName(name);
                carTypeAdapter.setType(type);
                carTypeAdapter.setLetter(letter);
                leftLv.setAdapter(carTypeAdapter);

            }

            @Override
            public void onError(String errorMsg) {

            }
        });

    }

    private void locationDrawable() {
        locationView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.right_drawer_location, null);
        locationCloseTv = (TextView) locationView.findViewById(R.id.drawer_locationforum_close);
        locationCloseTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openRightLayout();
                layoutForDrawer.removeView(locationView);
            }
        });
        locationRightLv = (ListView) locationView.findViewById(R.id.drawer_location_right_lv);
        orderAdapter = new OrderAdapter(this);
        orderAdapter.setOrder(locationOrder);
        locationRightLv.setAdapter(orderAdapter);
        locationRightLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int rightSection = 0;
                for (int i = 0; i < position; i++) {
                    rightSection += locationForumAdapter.getCountForSection(i) + 1;
                }
                locationLeftLv.setSelection(rightSection);
//                toastCustom.getToast(getApplicationContext(), letter[position]);
                ToastCustom.showText(getApplicationContext() , letter[position]);
            }
        });
        locationLeftLv = (PinnedHeaderListView) locationView.findViewById(R.id.drawer_location_left_lv);
        mNetTool.getNetData(URLValues.REGION_BBS_URL, LocationForumBean.class, new NetTool.NetListener<LocationForumBean>() {
            @Override
            public void onSuccess(LocationForumBean locationForumBean) {
                name = new ArrayList<>();
                ArrayList<String> a = new ArrayList<>();
                for (int num = 0; num < locationOrder.length; num++) {
                    for (int i = 0; i < locationForumBean.getResult().getList().size(); i++) {
                        if (locationForumBean.getResult().getList().get(i).getFirstletter().equals(locationOrder[num])) {
                            a.add(locationForumBean.getResult().getList().get(i).getBbsname());
                        }
                    }
                    name.add(a);
                    a = new ArrayList<>();
                }
                locationForumAdapter = new LocationForumAdapter(getApplicationContext());
                locationForumAdapter.setName(name);
                locationForumAdapter.setLetter(locationOrder);
                locationLeftLv.setAdapter(locationForumAdapter);

            }

            @Override
            public void onError(String errorMsg) {

            }
        });
    }

    private void themeDrawable() {
        themeView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.right_drawer_theme, null);
        themeClose = (TextView) themeView.findViewById(R.id.drawer_themeforum_close);
        themeClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openRightLayout();
                layoutForDrawer.removeView(themeClose);
            }
        });
        themeLv = (ListView) themeView.findViewById(R.id.drawer_theme_forum_lv);
        themeLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
        themeAdapter = new ThemeAdapter(getApplicationContext());
        mNetTool.getNetData(URLValues.THEME_BBS_URL, ThemeBean.class, new NetTool.NetListener<ThemeBean>() {
            @Override
            public void onSuccess(ThemeBean themeBean) {
                themeAdapter.setThemeBean(themeBean);
                themeLv.setAdapter(themeAdapter);
            }

            @Override
            public void onError(String errorMsg) {

            }
        });
    }
    private void videoTypeDrawable() {
        videoView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.right_drawer_video, null);
        videoClose = (TextView) videoView.findViewById(R.id.drawer_video_close);
        videoClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openRightLayout();
                layoutForDrawer.removeView(videoView);
            }
        });
        videoLv = (ListView) videoView.findViewById(R.id.drawer_video_lv);
        videoLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.putExtra("position" , position);
                intent.setAction(StringValues.CHANGETYPE);
                sendBroadcast(intent);
                openRightLayout();
                videoTypeAdapter.setSelection(position);

            }
        });

        String[] type = StringValues.type;
//                vt1 = 新车
//                vt2 = 试车
//                vt3 = 广告
//                vt4 = 花边
//                vt5 = 技术
//                vt6 = 客户
//                vt7 = 事件
//                vt8 = 原创
//                vt9 = 到店实拍
//                vt10 = 二手车

        videoTypeAdapter = new VideoTypeAdapter(getApplicationContext());
        videoTypeAdapter.setStrings(type);
        videoLv.setAdapter(videoTypeAdapter);

    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        searchIv.setVisibility(View.VISIBLE);
        modeIv.setVisibility(View.INVISIBLE);
        switch (checkedId) {
            case R.id.recommend_btn:
                recommendFragment = new RecommendFragment();
                fragmentTransaction.replace(R.id.frame_layout_main, recommendFragment);
                break;
            case R.id.forum_btn:
                ForumFragment forumFragment = new ForumFragment();
                fragmentTransaction.replace(R.id.frame_layout_main, forumFragment);
                break;
            case R.id.find_car_btn:
                fragmentTransaction.replace(R.id.frame_layout_main, new FindCarFragment());

                break;
            case R.id.find_btn:
                fragmentTransaction.replace(R.id.frame_layout_main, new FindFragment());
                break;
            case R.id.myself_btn:
                fragmentTransaction.replace(R.id.frame_layout_main, new MyselfFragment());
                searchIv.setVisibility(View.INVISIBLE);
                modeIv.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
        fragmentTransaction.commit();

    }


    public void openRightLayout() {
        if (drawerLayout.isDrawerOpen(layoutForDrawer)) {
            drawerLayout.closeDrawer(layoutForDrawer);
        } else {
            drawerLayout.openDrawer(layoutForDrawer);
        }
    }


    private void initEvent() {
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
            }

            @Override
            public void onDrawerOpened(View drawerView) {

                //菜单打开后，打开手势滑动操作，使可以手势滑回菜单
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                //菜单关闭后，再次关闭手势滑动操作，使不能手势滑出
                if (carTypeView != null) {
                    layoutForDrawer.removeView(carTypeView);
                }
                if (locationView != null) {
                    layoutForDrawer.removeView(locationView);
                }
                if (themeView != null) {
                    layoutForDrawer.removeView(themeView);
                }
                if (videoView != null) {
                    layoutForDrawer.removeView(videoView);
                }
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

    }

    private boolean closeActivity() {
        if (drawerLayout.isDrawerOpen(layoutForDrawer)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (closeActivity()) {
                drawerLayout.closeDrawer(layoutForDrawer);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
